import { createStore } from "vuex"

const store =  createStore({
    state: {
        user:null,
        token:''  //初始化token
    },
    mutations: {
        //存储token方法
        //设置token等于外部传递进来的值
        setToken(state, token) {
            state.token = token;
            //同步存储token至localStorage
            localStorage.setItem("token",token)
        },
        deleteToken(state){
            state.token = '';
            localStorage.removeItem("token");
        },
        setUser(state, user) {
            state.user = user;
            localStorage.setItem("user",user);
        },
        deleteUser(state){
            state.user = '';
            localStorage.setItem("user",null);
        },
    },
    getters : {
        //获取token方法
        //判断是否有token,如果没有重新赋值，返回给state的token
        getToken(state) {
            if (!state.token) {
                state.token = localStorage.getItem('token')
            }
            return state.token
        },
        getUser(state) {
            if (!state.user) {
                state.user = localStorage.getItem('user')
            }
            return state.user
        }
    },
    actions: {

    }
})

export default store






